package com.sharemedia.net
{
	import com.sharemedia.events.FeedbackEvent;
	import com.sharemedia.events.PeerEvent;
	
	import flash.events.NetStatusEvent;
	import flash.net.GroupSpecifier;
	import flash.net.NetStream;

	[Event(name="feedbackReceived", type="com.sharemedia.events.FeedbackEvent")]
	public class StreamPeer extends BasePeer
	{
		protected var netStream:NetStream;
		
		private var _streamName:String;
		
		public function StreamPeer()
		{
			super();
		}
		
		private var listener:Boolean;
		
		public function init(streamName:String, listener:Boolean=false):void
		{
			this.listener = listener;
			_streamName = streamName;
			initConnection();
		}
		
		protected function netStatusHandler(event:NetStatusEvent):void
		{
			logger.info(event.info.code);
		}
		
		override protected function setupStream():void
		{
			var groupSpec:GroupSpecifier = new GroupSpecifier(_streamName);
			groupSpec.serverChannelEnabled = true;
			groupSpec.multicastEnabled = true;
			groupSpec.postingEnabled = true;
			
			if(netStream)
				netStream.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);	
			
			netStream = new NetStream(netConnection, groupSpec.groupspecWithAuthorizations());
			netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			
			if(listener)
			{
				netStream.client = this;
				netStream.play("Feedback");
			}
			
			dispatchEvent(new PeerEvent(PeerEvent.PEER_CONNECTED));
		}
		
		private var publishing:Boolean; 
		public function send(trackUID:String, like:Boolean):void
		{
			if(!listener && !publishing)
				netStream.publish("Feedback");
			netStream.send("onFeedBack", trackUID, like);
		}
		
		public function onFeedBack(trackUID:String, like:Boolean):void
		{
			dispatchEvent(new FeedbackEvent(FeedbackEvent.FEEDBACK_RECEIVED, trackUID, like));
		}
	}
}